<template>
  <div class="import_step" v-if="dialogVisible">
    <el-dialog
      title="导入工单"
      :visible.sync="dialogVisible"
      width="600px"
      customClass="mes_dialog"
      v-dialogDrag
      :close-on-click-modal="false"
      :before-close="handleClose">
      <div class="step_one mes_file_secret" v-if="step === 1">
        <!--<div class="alert_msg">请先下载“导入模版”，修改后上传文件。</div>-->
        <div class="import_item">
          <div class="import_label"><span class="import_required">*</span>文档密级：</div>
          <div class="import_cont">
            <el-select v-model="secrecyGrade" size="small" placeholder="请选择密级">
              <el-option
                v-for="item in fileSecretLevel"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <!--<div class="import_item">-->
          <!--<div class="import_label"><span class="import_required">*</span>导入类型：</div>-->
          <!--<div class="type_radio import_cont">-->
            <!--<el-radio v-model="workOrderType" label="all">全部工单导入</el-radio>-->
            <!--<el-radio v-model="workOrderType" label="one">只导入工单表</el-radio>-->
          <!--</div>-->
        <!--</div>-->
        <div class="import_item">
          <div class="import_label"><span class="import_required">*</span>选择文件：</div>
          <div class="file_cont import_cont">
            <div class="mes_btn">
              <el-button class="file_btn" size="small" @click="$refs.fileInput.click()">
                <i class="iconfont icon-btn_addnew"></i>
                <span>选择文件</span>
                <input type="file"
                       ref="fileInput"
                       class="file_input"
                       :accept="accept.toString()"
                       @change="_file">
              </el-button>
              <span class="accept_text">支持{{accept.join('、')}}格式</span>
            </div>
            <div class="file_name_input" v-show="filesData && filesData.name">
              <i class="el-icon-document"></i>
              <tooltip-txt :text="filesData && filesData.name"></tooltip-txt>
            </div>
          </div>
        </div>
      </div>
      <div class="step_two" v-else-if="step === 2">
        <span>正在上传工单...</span>
        <div class="total_progress">
          <div class="current_progress" :style="{width: progress}">
            <span>{{progress}}</span>
          </div>
        </div>
      </div>
      <div class="step_three" v-else-if="step === 3">
        <div class="step_msg">
          <i class="iconfont icon-tishi"></i>
          <span class="step_msg_txt">上传失败，请重新上传</span>
        </div>
      </div>
      <div class="step_four" v-else-if="step === 4"
           v-loading="true"
           element-loading-text="数据校验中"
      ></div>
      <div class="step_five" v-else-if="step === 5">
        <div class="step_msg">
          <i class="iconfont icon-tishi"></i>
          <span class="step_msg_txt">验证失败，请重新验证或者关闭重传</span>
        </div>
      </div>
      <div class="step_six" v-else-if="step === 6">
        <div class="step_msg">
          <i class="iconfont icon-xiaoxitishi"></i>
          <span class="step_msg_txt">上传失败，请根据以下提示进行修改后再导入</span>
        </div>
        <div class="err_msg">
          <el-table :data="errData" max-height="440" :show-header="false" border>
            <el-table-column type="index" width="40" align="center"></el-table-column>
            <el-table-column
              :resizable="false"
              show-overflow-tooltip>
              <template slot-scope="scope">{{scope.row}}</template>
            </el-table-column>
          </el-table>
        </div>
        <div class="err_file">
            <span @click="_down" class="err_file_btn">
              <i class="iconfont icon-btn_download"></i>下载错误文档
            </span>
          <span class="err_file_msg">查看更多信息，请下载错误文档</span>
        </div>
      </div>
      <div class="step_seven" v-else-if="step === 7">
        <div class="step_msg">
          <i class="iconfont icon-zhengquetishi"></i>
          <span class="step_msg_txt">上传成功，请点击“继续”确认导入内容。</span>
        </div>
      </div>
      <span slot="footer" class="mes_btn">
      <el-button type="primary" v-if="step === 1" @click="confirmImport">导入</el-button>
      <el-button type="primary" v-else-if="step === 3" @click="handleClose(true)">重新导入</el-button>
      <el-button type="primary" v-else-if="step === 5" @click="verifyFile">重新验证</el-button>
      <el-button type="primary" v-else-if="step === 6" @click="handleClose">确定</el-button>
      <el-button type="primary" v-else-if="step === 7" @click="setDetail">继续</el-button>
      <el-button @click="handleClose" v-if="step !== 7 && step !== 6">取消</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ImportStep',
  data() {
    return {
      dialogVisible: false, // 是否显示
      // 文件类型
      accept: ['.xls', '.xlsx'],
      secrecyGrade: this.defaultFileLevel, // 文档密级
      workOrderType: 'all', // 导入工单类型
      step: 1, // 当前步骤
      filesData: null, // file文件对象
      errData: [], // 错误数据
      progress: '0%', // 上传进度
      filePath: '', // 文件上传地址
      importToken: null, // 导入token
      verifyToken: null, // 验证token
    }
  },
  computed: {
    // 文件保密级别
    fileSecretLevel() {
      return this.$store.state.dict.fileSecretLevel.labels || []
    }
  },
  methods: {
    // 打开方法
    openDialog() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.fileInput.value = null
      })
    },
    // 选择文件
    _file(e) {
      let file = e.target.files[0]
      if (file && /^(\.xls)|(xlsx)$/.test(file.name.slice(-4).toLowerCase())) {
        this.filesData = file
        e.target.value = null
      } else if (file) {
        this.filesData = null
        this.$message({
          type: 'error',
          message: `文件格式错误，请选择后缀为${this.accept.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      }
    },
    // 判断是否可以上传
    confirmImport() {
      if (!this.secrecyGrade) {
        this.$message({
          type: 'error',
          message: '请先选择文档密级',
          duration: 1500,
          center: true
        })
      } else if (!this.workOrderType) {
        this.$message({
          type: 'error',
          message: '请先选择导入类型',
          duration: 1500,
          center: true
        })
      } else if (!this.filesData) {
        this.$message({
          type: 'error',
          message: `请先选择后缀为${this.accept.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      } else {
        this.step = 2
        this.importFile()
      }
    },
    // 上传进度回调
    progressBar(progressEvent) {
      if (progressEvent.lengthComputable) {
        this.progress = parseInt(progressEvent.loaded / progressEvent.total * 100) + '%'
      }
    },
    // 上传文件
    importFile() {
      this.importToken = this.$axios.CancelToken.source()
      let formdata = new FormData()
      formdata.append('file', this.filesData)
      formdata.append('fileSecretLevel', this.secrecyGrade)
      this.$store.dispatch('importFile', {
        data: formdata,
        onUploadProgress: this.progressBar,
        cancelToken: this.importToken.token,
      }).then(res => {
        this.filePath = res.filePath
        this.verifyFile()
      }).catch(() => {
        this.step = 3
      })
    },
    // 验证文件格式
    verifyFile() {
      this.step = 4
      this.verifyToken = this.$axios.CancelToken.source()
      // let verifyUrl = this.workOrderType === 'all' ? 'a/workorder/workorderExcel/verify' : this.workOrderType === 'one' ? 'a/workorder/workorderExcel/verifytask' : ''
      let verifyUrl = 'a/workorder/workorderExcel/verify'
      return this.$store.dispatch('saveData', {
        method: 'post',
        url: verifyUrl,
        data: {
          path: this.filePath,
          fileName: this.filesData.name
        },
        cancelToken: this.verifyToken.token,
        noCommit: true
      }).then(res => {
        this.errData = res.data
        if (!res.data.length) {
          this.step = 7
        } else {
          this.errData = res.data
          this.step = 6
        }
      }).catch(() => {
        this.step = 5
      })
    },
    // 下载错误文档
    _down() {
      if (this.errData.length) {
        this.$downloadErrorFile('导入工单错误信息.txt', this.errData.join('\r\n'))
      }
    },
    // 查看导入数据
    setDetail() {
      if (!this.filePath || this.step !== 7) return
      // let previewName = this.workOrderType === 'all' ? 'importDetail' : this.workOrderType === 'one' ? 'workOrderPreview' : ''
      let previewName = 'importDetail'
      this.$router.push({
        name: previewName,
        params: {
          id: this.filePath
        },
        query: {
          fileName: this.filesData.name,
          fileSize: this.filesData.size,
          fileGrade: this.secrecyGrade
        }
      })
      this.dialogVisible = false
      this.secrecyGrade = this.defaultFileLevel
      this.clearData()
    },
    // 清空重置
    clearData() {
      this.filesData = null
      this.importToken = null
      this.verifyToken = null
      this.errData = []
      this.progress = '0%'
      this.filePath = ''
      this.step = 1
    },
    // 关闭弹框
    handleClose(val) {
      switch (this.step) {
        case 1:
        case 5:
        case 6:
        case 7:
          this.dialogVisible = false
          this.workOrderType = 'all'
          this.secrecyGrade = this.defaultFileLevel
          this.clearData()
          break
        case 3:
          if (val !== true) {
            this.dialogVisible = false
            this.workOrderType = 'all'
            this.secrecyGrade = this.defaultFileLevel
          }
          this.clearData()
          break
        case 2:
          this.importToken.cancel('终止上传')
          this.step = 3
          break
        case 4:
          this.verifyToken.cancel('终止验证')
          this.step = 5
          break
      }
    }
  }
}
</script>

<style scoped lang="less">
  .import_step {
    .el-dialog__body {
      padding: 20px;
      .step_one {
        .alert_msg {
          height: 16px;
          line-height: 16px;
          margin-bottom: 15px;
          font-size: 14px;
          color: @mesFontDefault;
        }
        .type_radio {
          display: flex;
          align-items: center;
        }
      }
      .step_two {
        width: 100%;
        .total_progress {
          margin: 20px 0;
          width: 100%;
          height: 20px;
          background-color: @mesBgDefault;
          border-radius: 2px;
          overflow: hidden;
          .current_progress {
            height: 20px;
            background: url(./../../../../../assets/img/bg_loading.png) top left;
            background-size: 100%;
            font-size: 12px;
            color: @mesFontWhite;
            line-height: 20px;
            text-align: right;
          }
        }
      }
      .step_four {
        height: 90px;
      }
      .step_three, .step_five {
        padding: 20px;
        .step_msg {
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          color: @mesFontRed;
          .step_msg_txt {
            height: 16px;
            line-height: 16px;
          }
          .icon-tishi {
            font-size: 24px;
            margin-right: 5px;
            margin-top: -3px;
          }
        }
      }
      .step_six {
        .step_msg {
          color: @mesFontRed;
          font-size: 14px;
          margin-bottom: 20px;
          .icon-xiaoxitishi {
            font-size: 16px;
            margin-right: 3px;
          }
        }
        .err_file {
          display: flex;
          align-items: center;
          margin-top: 20px;
          .err_file_btn {
            flex: 0 0 130px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            color: #333;
            font-size: 14px;
            text-decoration: none;
            background-color: @mesBgWhite;
            border: @mesBorDefault;
            margin-right: 5px;
            cursor: pointer;
            .icon-btn_download {
              color: @mesIconDown;
              margin-right: 5px;
            }
          }
          .err_file_msg {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: @mesFontDefault;
            font-size: 14px;
          }
        }
      }
      .step_seven {
        padding: 20px;
        .step_msg {
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          color: #333;
          .step_msg_txt {
            height: 16px;
            line-height: 16px;
          }
          .icon-zhengquetishi {
            color: @mesFontSuccess;
            font-size: 24px;
            margin-right: 5px;
          }
        }
      }
    }
  }
</style>
<style lang="less">
  .import_step {
    .step_four {
      .el-loading-spinner {
        margin-top: -40px;
      }
      .el-loading-text {
        padding-top: 10px;
        color: #333;
      }
    }
    .step_six {
      .el-table td:first-child .cell {
        padding: 0 5px;
      }
    }
    .err_msg {
      .el-table td {
        padding: 0;
        height: 30px;
        line-height: 30px;
      }
    }
  }
</style>
